package com.schoolai.schoolset.auth.service;

import com.nimbusds.jose.JOSEException;
import com.schoolai.util.tools.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.GeneralSecurityException;
import java.security.interfaces.RSAPublicKey;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * Copyright(C),2019-2025，XX公司
 * FileName:JwtTokenProvider
 * Author:bobby
 * 创建时间：2025/10/22 09:24
 * Description:bobby1222
 * History:
 * <auth>        <time>       <version>       <desc>
 * 作者          修改时间       版本号         描述
 */
@Slf4j
@Service
public class JwtTokenProvider {
    public Authentication getAuthentication(String token) throws IOException, GeneralSecurityException, ParseException, JOSEException {
        // 1、加载公钥
        String publicKeyFilePath="public.txt";
        ClassPathResource classpathResource = new ClassPathResource(publicKeyFilePath);
        InputStream inputStream = classpathResource.getInputStream();
        String publicKeyKeyContent = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        RSAPublicKey publicKey = JWTUtil.loadPublicKeyFromFile(publicKeyKeyContent);
        JWTUtil jwtUtil = new JWTUtil();
        JWTUtil.VerificationResult result = jwtUtil.verifyToken(publicKey,token);

        if (result.isValid()) {
            List list= (List)result.getClaims().getClaim("authorities");
            // 4. 封装权限信息（权限标识符code）
            List<GrantedAuthority> authorities = new ArrayList<>();
            list.forEach(grantedAuthority->{
                // System.out.println("权限:"+grantedAuthority);
                authorities.add(new SimpleGrantedAuthority(grantedAuthority.toString()));
            });
            JwtUser jwtUser = new JwtUser(
                    (String) result.getClaims().getClaim("uid"),
                    (String) result.getClaims().getClaim("username"),
                    (String) result.getClaims().getClaim("password"),
                    (String) result.getClaims().getClaim("nickName"),
                    (String) result.getClaims().getClaim("imageUrl"),
                    (String) result.getClaims().getClaim("mobile"),
                    (String) result.getClaims().getClaim("email"),
                    (Boolean)result.getClaims().getClaim("isAccountNonExpired")?1:0,
                    (Boolean)result.getClaims().getClaim("isAccountNonLocked")?1:0,
                    (Boolean)result.getClaims().getClaim("isCredentialsNonExpired")?1:0,
                    (Boolean)result.getClaims().getClaim("isEnabled")?1:0,
                    authorities );
            return new UsernamePasswordAuthenticationToken(jwtUser, "", authorities); // 创建 Authentication 对象并返回，空密码和权限列表可以根据实际情况调整
        } else {
            log.info("✗ 令牌验证失败: " + result.getMessage());

        }
       return null;
    }
}
